package cn.newgrand.netcall.consultant.ui;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.KeyStroke;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;

import org.jivesoftware.resource.Res;
import org.jivesoftware.resource.SparkRes;
import org.jivesoftware.spark.ChatAreaSendField;
import org.jivesoftware.spark.ChatManager;
import org.jivesoftware.spark.SparkManager;
import org.jivesoftware.spark.component.TitlePanel;
import org.jivesoftware.spark.ui.ChatInputEditor;
import org.jivesoftware.spark.ui.ContainerComponent;
import org.jivesoftware.spark.util.ResourceUtils;
import org.jivesoftware.spark.util.log.Log;
import org.jivesoftware.sparkimpl.plugin.alerts.SparkToaster;
import org.jivesoftware.sparkimpl.settings.local.LocalPreferences;
import org.jivesoftware.sparkimpl.settings.local.SettingsManager;

import cn.newgrand.smackx.consultant.ConsultantManager;

public class LeaveWordSendPanel extends JPanel implements ContainerComponent , DocumentListener{
	
	private String tabTitle;
	private String frameTitle;
	private JLabel titleLabel;
	private JButton sendButton;
	private ChatAreaSendField chatArea;
	private String spid;
	private String user;
	private String trueName;
	private KeyAdapter chatEditorKeyListener;
	private JDialog dlg;
	
	public LeaveWordSendPanel(String spid,String user,String trueName){
		this.setLayout(new GridBagLayout());
		this.spid = spid;
		this.user = user;
		this.trueName = trueName;
		tabTitle = "留言";
		frameTitle = "留言";
		titleLabel = new JLabel("");
		chatArea = new ChatAreaSendField("");
		chatArea.getScrollPane().setPreferredSize(new Dimension(410, 200));
		sendButton = new JButton();
		ResourceUtils.resButton(sendButton, "发送留言");
		sendButton.setEnabled(false);
		sendButton.addActionListener(new SendLeavewordListener());
		//add(titleLabel, new GridBagConstraints(0, 0, 1, 1, 1.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0));
		add(chatArea, new GridBagConstraints(0, 0, 1, 1, 1.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
		add(sendButton, new GridBagConstraints(0, 1, 1, 1, 1.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
		 // Add to Chat window
//        ChatManager chatManager = SparkManager.getChatManager();
//        chatManager.getChatContainer().addContainerComponent(this);
		//this.setSize(300, 200);
		chatEditorKeyListener = new KeyAdapter() {
            public void keyPressed(KeyEvent e) {
                checkForEnter(e);
                //resizePreferSizeToLast();
            }

        };
        getChatInputEditor().addKeyListener(chatEditorKeyListener);
        getChatInputEditor().getDocument().addDocumentListener(this);
		createDialog();
	}
	
	public class SendLeavewordListener implements ActionListener{

		@Override
		public void actionPerformed(ActionEvent e) {
			sendMessage();
			getChatInputEditor().clear();
			dlg.setVisible(false);
		}
		
	}
	
	private String getDisplayName(){
		if(trueName != null && !"".equals(trueName)){
			return trueName;
		}else if(spid != null && !"".equals(spid)){
			return spid;
		}else if(user != null && !"".equals(user)){
			return user;
		}else{
			return "";
		}
	}

	private void createDialog() {
		final JOptionPane pane;

        TitlePanel titlePanel;

        // Create the title panel for this dialog
        titlePanel = new TitlePanel("", "专家["+getDisplayName()+"]不在线,您可以留言,专家上线后会及时给您回复.", SparkRes.getImageIcon(SparkRes.BLANK_24x24), true);

        // Construct main panel w/ layout.
        final JPanel mainPanel = new JPanel();
        mainPanel.setLayout(new BorderLayout());
        mainPanel.add(titlePanel, BorderLayout.NORTH);
        
        // The user should only be able to close this dialog.
        Object[] options = {Res.getString("close")};
        pane = new JOptionPane(this, JOptionPane.PLAIN_MESSAGE, JOptionPane.OK_CANCEL_OPTION, null, options, options[0]);
        
        mainPanel.add(this, BorderLayout.CENTER);

        JOptionPane p = new JOptionPane();
        dlg = p.createDialog(SparkManager.getMainWindow(), "留言");
        dlg.pack();
        dlg.setSize(440, 340);
        dlg.setContentPane(mainPanel);
        dlg.setLocationRelativeTo(SparkManager.getMainWindow());
        
        PropertyChangeListener changeListener = new PropertyChangeListener() {
            public void propertyChange(PropertyChangeEvent e) {
                Object o = pane.getValue();
                if (o instanceof Integer) {
                    dlg.setVisible(false);
                    return;
                }

                String value = (String)pane.getValue();
                if (Res.getString("close").equals(value)) {
                    dlg.setVisible(false);
                }
            }

        };

        pane.addPropertyChangeListener(changeListener);
        dlg.setResizable(false);
        dlg.setVisible(true);
        dlg.toFront();
        dlg.requestFocus();
	}

	@Override
	public String getTabTitle() {
		// TODO Auto-generated method stub
		return tabTitle;
	}

	@Override
	public String getFrameTitle() {
		// TODO Auto-generated method stub
		return frameTitle;
	}

	@Override
	public ImageIcon getTabIcon() {
		// TODO Auto-generated method stub
		return SparkRes.getImageIcon(SparkRes.CONFERENCE_IMAGE_16x16);
	}

	@Override
	public JComponent getGUI() {
		// TODO Auto-generated method stub
		return this;
	}

	@Override
	public String getToolTipDescription() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public boolean closing() {
		// TODO Auto-generated method stub
		ChatManager chatManager = SparkManager.getChatManager();
        chatManager.getChatContainer().closeTab(this);
		return false;
	}
	
	protected void sendMessage(){
		String body = chatArea.getText();
		ConsultantManager.getInstance(SparkManager.getConnection()).sendLeavewordPacket(user, spid,body);
		//直接提示留言成功...
		SparkToaster toaster = new SparkToaster();
        toaster.setNotifyShowForever(false);
        toaster.setDisplayTime(2000);
        toaster.setBorder(BorderFactory.createBevelBorder(0));
        toaster.setTitle(Res.getString("title.notification"));
        toaster.setViewLabelString("");
        toaster.showToaster("留言成功!");
	}
	
	private void checkForEnter(KeyEvent e) {
    	final LocalPreferences pref = SettingsManager.getLocalPreferences();
    	final KeyStroke keyStroke = KeyStroke.getKeyStroke(e.getKeyCode(), e.getModifiers());
    	// IF there is no body, just return and do nothing
        if (!keyStroke.equals(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, KeyEvent.SHIFT_DOWN_MASK)) &&
                e.getKeyChar() == KeyEvent.VK_ENTER && pref.getHotKeySendMessage().equals("Enter")) {
            e.consume();
            sendMessage();
            getChatInputEditor().setText("");
            getChatInputEditor().clear();
            getChatInputEditor().setCaretPosition(0);
            dlg.setVisible(false);
        }else if (keyStroke.equals(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, KeyEvent.CTRL_DOWN_MASK)) &&
                e.getKeyChar() == KeyEvent.VK_ENTER && pref.getHotKeySendMessage()!="Enter") {
            e.consume();
            sendMessage();
            getChatInputEditor().setText("");
            getChatInputEditor().clear();
            getChatInputEditor().setCaretPosition(0);
            dlg.setVisible(false);
        }
        else if (keyStroke.equals(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, KeyEvent.SHIFT_DOWN_MASK))) {
            final Document document = getChatInputEditor().getDocument();
            try {
                document.insertString(getChatInputEditor().getCaretPosition(), "\n", null);
                getChatInputEditor().requestFocusInWindow();
                sendButton.setEnabled(true);
            }
            catch (BadLocationException badLoc) {
                Log.error("Error when checking for enter:", badLoc);
            }
        }
	}
	
	public ChatInputEditor getChatInputEditor() {
        return chatArea.getChatInputArea();
    }
	
	protected void checkForText(DocumentEvent e) {
        final int length = e.getDocument().getLength();
        if (length > 0) {
//            chatAreaButton.getButton().setEnabled(true);
        	sendButton.setEnabled(true);
        }
        else {
//            chatAreaButton.getButton().setEnabled(false);
        	sendButton.setEnabled(false);
        }
//        resizePreferSizeToLast();
//        verticalSplit.setDividerLocation(-1);
    }

	@Override
	public void insertUpdate(DocumentEvent e) {
		checkForText(e);
	}

	@Override
	public void removeUpdate(DocumentEvent e) {
		checkForText(e);
	}

	@Override
	public void changedUpdate(DocumentEvent e) {
		
	}
	
	

}
